package com.example.book.sys.web;

import com.example.book.common.shiro.ShiroUtils;
import com.example.book.common.utils.Constants;
import com.example.book.common.utils.LocalFileUtils;
import com.example.book.domain.sys.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

@Controller
@RequestMapping("/profile")
public class CkController {

    @Value("${system.ck_http}")
    private String ck_http;

    @Value("${system.profile.path}")
    private String profile;

    @Value("${system.profile.real_path}")
    private String realProfile;

    /**
     * ckeditor图片上传
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/profile/ckUpload")
    public void ckedtorImageUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {

        SysUser sysUser = ShiroUtils.getUser();

        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

        String path = null;

        if (commonsMultipartResolver != null) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile mfile = multiRequest.getFile(iter.next());
                path = ck_http + LocalFileUtils.upload(sysUser.getId(), profile, realProfile, mfile);
            }
        }

        response.setContentType("text/html;charset=UTF-8");
        String callback = request.getParameter("CKEditorFuncNum");
        try {
            PrintWriter out = response.getWriter();
            out.print("<script type=\"text/javascript\">");
            out.print("window.parent.CKEDITOR.tools.callFunction(" + 0 + ",'" + path.replaceAll("\\\\", "/") + "',''" + ")");
            out.print("</script>");
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
